<template>
  <y-dialog @open="open" @close="emit('close')" width="1000px" append-to-body>
    <el-form
      ref="addRef"
      :model="form"
      :rules="rules"
      size="default"
      label-width="120px"
      v-loading="loading"
    >
      <el-row>
        <el-col>
          <el-form-item label="需求名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入需求名称"
              clearable
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属产品" prop="product">
            <y-select
              v-model="form.product"
              placeholder="请选择所属产品"
              :optionsFunc="listProduct"
              @change="changeProductOptions"
              :disabled="['update', 'change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="优先级" prop="priority">
            <y-select
              v-model="form.priority"
              placeholder="请选择优先级"
              :options="sys_priority_level"
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row> </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人" prop="owner">
            <y-select
              v-model="form.owner"
              placeholder="请选择负责人"
              :optionsFunc="listUser"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评审人" prop="reviewers">
            <y-select
              v-model="form.reviewers"
              placeholder="请选择评审人"
              :optionsFunc="listUser"
              multiple
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="需求来源" prop="origin">
            <y-select
              v-model="form.origin"
              placeholder="请选择需求来源"
              :options="pms_req_origin"
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="需求分类" prop="classify">
            <y-select
              v-model="form.classify"
              placeholder="请选择需求分类"
              :options="pms_req_classify"
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属模块" prop="module">
            <y-tree-select
              v-model="form.module"
              placeholder="请选择所属模块"
              :optionsFunc="selectModule"
              :optionsParams="queryParams"
              @change="changeModuleOptions"
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属版本" prop="version">
            <y-tree-select
              v-model="form.version"
              placeholder="请选择所属版本"
              :optionsFunc="selectVersion"
              :optionsParams="queryParams"
              @change="changeVersionOptions"
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="父需求" prop="parent">
            <y-tree-select
              v-model="form.parent"
              placeholder="请选择父需求"
              :optionsFunc="selectRequirement"
              :optionsParams="queryParams"
              @change="handleParentChanged"
              :disabled="['change'].includes(props.operate)"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="需求描述" prop="desc">
            <y-editor
              editorId="editorReqDecs"
              v-model="form.desc"
              placeholder="请输入需求描述"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="验收标准" prop="criteria">
            <y-editor
              editorId="editorReqCriterria"
              v-model="form.criteria"
              placeholder="请输入验收标准"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="备注" prop="remark">
            <y-editor
              editorId="editorReqRemark"
              v-model="form.remark"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="标签" prop="tags">
            <y-tag v-model="form.tags" :closable="true" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit($event, 'submit')"
          >确定</el-button
        >
        <el-button type="warning" @click="submit($event, 'save')"
          >存为草稿</el-button
        >
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="AuReq">
import { listProduct } from "@/api/pms/product";
import { treeselect as selectModule } from "@/api/pms/module";
import { treeselect as selectVersion } from "@/api/pms/version";
import { treeselect as selectRequirement } from "@/api/pms/requirement";
import { listUser } from "@/api/sys/user";

const { proxy } = getCurrentInstance();
const { sys_priority_level, pms_req_origin, pms_req_classify } = proxy.useDict(
  "sys_priority_level",
  "pms_req_origin",
  "pms_req_classify"
);

const loading = ref(false);
const emit = defineEmits(["submited", "close"]);

const data = reactive({
  form: {},
  queryParams: {
    product: undefined,
    module: undefined,
    version: undefined,
  },
  rules: {
    product: [{ required: true, message: "所属产品不能为空", trigger: "blur" }],
    name: [{ required: true, message: "需求名称不能为空", trigger: "blur" }],
    owner: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
    priority: [{ required: true, message: "优先级不能为空", trigger: "blur" }],
    origin: [{ required: true, message: "需求来源不能为空", trigger: "blur" }],
    classify: [
      { required: true, message: "需求分类不能为空", trigger: "blur" },
    ],
    desc: [{ required: true, message: "需求描述不能为空", trigger: "blur" }],
    criteria: [
      { required: true, message: "验收标准不能为空", trigger: "blur" },
    ],
    reviewers: [{ required: true, message: "评审人不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const props = defineProps({
  id: { type: String, default: "" },
  operate: { type: String, default: "add" },
  getMethod: { type: Function, default: undefined },
  addMethod: { type: Function, default: undefined },
  updateMethod: { type: Function, default: undefined },
});

/** 获取选中的产品对象信息 */
function changeProductOptions(val) {
  queryParams.value.product = val;
  form.value.parent = undefined;
}

/** 获取选中的模块对象信息 */
function changeModuleOptions(val) {
  queryParams.value.module = val;
}

/** 获取选中的版本对象信息 */
function changeVersionOptions(val) {
  queryParams.value.verison = val;
}

/** 限制父需求非当前需求 */
function handleParentChanged(val) {
  if (form.value.id == val) {
    proxy.$modal.msgWarning("不应选择该需求为父需求");
    form.value.parent = undefined;
  }
}

/** 更新标签方法 */
function handleTagsUpdate(data) {
  form.value.tags = data;
}

/** 打开对话框事件 */
async function open() {
  switch (props.operate) {
    case "change":
    case "update":
      loading.value = true;
      try {
        const response = await props.getMethod(props.id);
        form.value = response.data;
        queryParams.value.product = form.value.product.value;
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        loading.value = false;
      }
      break;
    default:
      reset();
      break;
  }
}

/** 重置Form方法 */
function reset() {
  form.value = {
    status: "draft",
    priority: "0",
    origin: "0",
    classify: "0",
    desc: "",
    criteria: "",
    remark: "",
  };
  proxy.resetForm("addRef");
}

/** 提交按钮事件 */
async function submit(value, type) {
  // 异步验证表单
  const valid = await new Promise((resolve) => {
    proxy.$refs["addRef"].validate(resolve);
  });
  if (!valid) return;

  try {
    // 若选择存储为 "草稿"，则修改需求状态为草稿，否则修改需求状态为 "评审中"
    form.value.status = type === "save" ? "draft" : "reviewing";
    if (form.value.id != undefined) {
      // 需求修改后，将状态置为"评审中"，并清空已评审信息
      form.value.review_result = "";
      form.value.review_remark = "";
      form.value.closed_type = "";
      form.value.closed_remark = "";
      form.value.reviewers = proxy.formatOptions(form.value.reviewers);
      await props.updateMethod(form.value);
      proxy.$modal.msgSuccess("修改成功");
    } else {
      await props.addMethod(form.value);
      proxy.$modal.msgSuccess("新增成功");
    }
    submited();
  } catch (error) {
    console.error("Submission failed:", error);
    proxy.$modal.msgError("提交失败：" + error.message);
  }
}

/** submited事件 */
function submited() {
  emit("submited");
  emit("close");
}
</script>
